package com.example.scannertest;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import android.view.MotionEvent;
import android.widget.*;
import com.google.zxing.client.android.CaptureActivity;
import java.io.IOException;
import java.net.*;

import android.os.Handler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    public static final int SCAN_CODE = 1;
    public static String SERVERIP = "10.96.130.129";
    public static int SERVERPORT = 60000;
    public static final int SENDPORT = 50000;
    public TextView text1;
    public EditText input;
    public int flag = 1;
    public Button btn;
    public boolean start;
    public Handler Handler;
    public String IP_PORT;
    public String X_Y;
    public int x1,y1;
    public int x0,y0;
    public String Instructions;
    private SensorManager sensorManager;
    private MySensorEventListener sensorEventListener;
    FrameLayout ppt_ctrl_Buttons;
    FrameLayout ms_ctrl_Buttons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sensorEventListener = new MySensorEventListener();
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        ppt_ctrl_Buttons = (FrameLayout)findViewById(R.id.ppt_btn_lout);
        ms_ctrl_Buttons = (FrameLayout)findViewById(R.id.ms_ctrl_lout);
        final Button set_now = (Button)findViewById(R.id.set_now);
        x0 = 0;y0 = 0;
        set_now.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String [] a ;
                a = X_Y.split(",");
                x0 += Integer.parseInt(a[1]);
                y0 += Integer.parseInt(a[2]);
            }
        });



        Button scan_button = (Button) findViewById(R.id.scan_button);
        scan_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, SCAN_CODE);
                set_now.setVisibility(View.VISIBLE);
            }
        });

        Button Left_Button = (Button) findViewById(R.id.left);
        Button Right_Button = (Button) findViewById(R.id.right);
        Button Mid_Button = (Button)findViewById(R.id.middle);
        Button Up_Button = (Button) findViewById(R.id.up);
        Button Down_Button = (Button) findViewById(R.id.down);
        Button ppt_ctrl =(Button)findViewById(R.id.ppt_ctrl);
        Button F = (Button)findViewById(R.id.f);
        Button P = (Button)findViewById(R.id.p);
        Button N = (Button)findViewById(R.id.n);
        Button W = (Button)findViewById(R.id.w);
        Button B = (Button)findViewById(R.id.b);
        Button Q = (Button)findViewById(R.id.q);
        Button H = (Button)findViewById(R.id.h);
        Button E = (Button)findViewById(R.id.e);
        Button ms_ctrl = (Button)findViewById(R.id.ms_ctrl);

        buttonListener btnlistener0 = new buttonListener();
        buttonListener btnlistener1 = new buttonListener();
        buttonListener btnlistener2 = new buttonListener();
        buttonListener btnlistener3 = new buttonListener();
        buttonListener btnlistener4 = new buttonListener();
        buttonListener btnlistener5 = new buttonListener();
        buttonListener btnlistener6 = new buttonListener();
        buttonListener btnlistener7 = new buttonListener();
        buttonListener btnlistener8 = new buttonListener();
        buttonListener btnlistener9 = new buttonListener();
        buttonListener btnlistener10 = new buttonListener();
        buttonListener btnlistener11 = new buttonListener();
        buttonListener btnlistener12 = new buttonListener();
        buttonListener btnlistener13 = new buttonListener();
        buttonListener btnlistener14 = new buttonListener();
        buttonListener btnlistener15 = new buttonListener();

        Left_Button.setOnTouchListener(btnlistener0);

        Left_Button.setOnClickListener(btnlistener1);
        Right_Button.setOnClickListener(btnlistener2);
        Mid_Button.setOnClickListener(btnlistener3);
        Up_Button.setOnClickListener(btnlistener4);
        Down_Button.setOnClickListener(btnlistener5);
        ppt_ctrl.setOnClickListener(btnlistener6);

        F.setOnClickListener(btnlistener7);
        P.setOnClickListener(btnlistener8);
        N.setOnClickListener(btnlistener9);
        W.setOnClickListener(btnlistener10);
        B.setOnClickListener(btnlistener11);
        Q.setOnClickListener(btnlistener12);
        H.setOnClickListener(btnlistener13);
        E.setOnClickListener(btnlistener14);
        ms_ctrl.setOnClickListener(btnlistener15);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SCAN_CODE:
                TextView scanResult = (TextView) findViewById(R.id.scan_result);
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra("scan_result");
                    scanResult.setText(result);
                    IP_PORT = result;//将扫描到的ip地址传到IP_PORT变量里面
                    new Thread(new Client()).start();//开始连接PC端的线程
                } else if (resultCode == RESULT_CANCELED) {
                    IP_PORT = "10.96.118.10,60000";//设置为试调机器的ip 用TCPSOCKET工具
                    new Thread(new Client()).start();//开始连接PC端的线程
                    scanResult.setText("没有扫描出结果");
                }
                break;
            default:
                break;
        }
    }


    public class Client implements Runnable {
        @Override
        public void run(){
            String [] ip_port = IP_PORT.split(",",2);
            SERVERIP = ip_port[0];
            SERVERPORT = Integer.parseInt(ip_port[1],10);
            try{
                InetAddress serverAddr = InetAddress.getByName(SERVERIP);
                DatagramSocket socket = new DatagramSocket(SENDPORT);
                byte[] buf;
                DatagramPacket packet;
                Instructions = "3,B";//开始标志
                buf  = Instructions.getBytes();
                packet = new DatagramPacket(buf, buf.length,
                        serverAddr, SERVERPORT);
                socket.send(packet);
                while(true){
                    try {
                        while(flag == 1){
                            buf = X_Y.getBytes();
                            packet= new DatagramPacket(buf, buf.length,
                                    serverAddr, SERVERPORT);
                            socket.send(packet);
                            Thread.sleep(10);
                        }

                        if(flag==0){
                            buf = Instructions.getBytes();
                            packet= new DatagramPacket(buf, buf.length,
                                    serverAddr, SERVERPORT);
                            socket.send(packet);
                            Thread.sleep(10);
                            flag = 1;
                        }
                        Thread.sleep(10);

                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    protected  void onPause(){
        //在空闲时间解除对传感器的监听，节省资源
        sensorManager.unregisterListener(sensorEventListener);
        super.onPause();
    }
    protected  void onResume(){
        //获取方向传感器
        Sensor orientationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sensorManager.registerListener(sensorEventListener, orientationSensor, SensorManager.SENSOR_DELAY_NORMAL);

        //获取加速度传感器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
        super.onResume();

    }

    private final class MySensorEventListener implements SensorEventListener{

        @Override
        public void onSensorChanged(SensorEvent event) {
            if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
                int x = Math.round(event.values[SensorManager.DATA_X])-x0;
                int y = Math.round(event.values[SensorManager.DATA_Y])-y0;
                //int z = Math.round(event.values[SensorManager.DATA_Z]);
                X_Y = "0," + x + "," + y;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    class buttonListener implements OnClickListener,View.OnTouchListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.right:
                    Instructions = "1,2";
                    flag = 0;
                    break;
                case R.id.left:
                    Instructions = "1,8";
                    flag = 0;
                    break;
                case R.id.up:
                    Instructions = "1,9";
                    flag = 0;
                    break;
                case R.id.down:
                    Instructions = "1,6";
                    flag = 0;
                    break;
                case R.id.middle:
                    Instructions = "1,3";
                    flag = 0;
                    break;
                case R.id.ppt_ctrl:
                    ms_ctrl_Buttons.setVisibility(View.GONE);
                    ppt_ctrl_Buttons.setVisibility(View.VISIBLE);
                    break;
                case R.id.f:
                    Instructions = "2,F";
                    flag = 0;
                    break;
                case R.id.p:
                    Instructions = "2,P";
                    flag = 0;
                    break;
                case R.id.n:
                    Instructions = "2,N";
                    flag = 0;
                    break;
                case R.id.w:
                    Instructions = "2,W";
                    flag = 0;
                    break;
                case R.id.b:
                    Instructions = "2,B";
                    flag = 0;
                    break;
                case R.id.q:
                    Instructions = "2,Q";
                    flag = 0;
                    break;
                case R.id.h:
                    Instructions = "2,H";
                    flag = 0;
                    break;
                case R.id.e:
                    Instructions = "2,E";
                    flag = 0;
                    break;
                case R.id.ms_ctrl:
                    ppt_ctrl_Buttons.setVisibility(View.GONE);
                    ms_ctrl_Buttons.setVisibility(View.VISIBLE);
                    break;
                default:
                    Instructions = "1,8";
                    flag = 0;
                    break;

            }

        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (v.getId()){
                case R.id.left:
                    if(event.getAction()==MotionEvent.ACTION_DOWN){
                        Instructions = "1,1";
                        flag = 0;
                    }
                    if(event.getAction()==MotionEvent.ACTION_UP){
                        Instructions = "1,0";
                        flag = 0;
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    }

}
